import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:fsharing/core/models/me.dart';
import 'package:fsharing/core/services/auth.dart';
import 'package:fsharing/core/viewmodels/pages/mine/user_realname_delete_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/user_realname_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/req_code_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/user_realname_query_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/main.dart';
import 'package:fsharing/ui/widgets/background_container.dart';
import 'package:fsharing/ui/widgets/count_down_text.dart';
import 'package:fsharing/ui/widgets/login_button.dart';
import 'package:fsharing/ui/widgets/round_back_button.dart';
import 'package:image_picker/image_picker.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';

class AuthPage extends StatelessWidget {
  final Me me;

  AuthPage({
    Key key,
    @required this.me,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var auth = Provider.of<Auth>(context, listen: false);
    return MultiProvider(
      providers: [
        Provider.value(value: me),
        ChangeNotifierProvider(create: (context) => UserRealnameQueryModel(auth)),
      ],
      child: BackgroundContainer(
        child: Scaffold(
          appBar: AppBar(
            leading: RoundBackButton(),
            title: Text('实名认证'),
          ),
          body: Consumer<UserRealnameQueryModel>(
            builder: (context, model, child) {
              switch (model.viewState) {
                case ViewState.busy:
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                case ViewState.error:
                  return Center(
                    child: Text(model.errorMessage),
                  );
                case ViewState.success:
                  return _SuccessWidget();
                default:
                  return Container();
              }
            },
          ),
        ),
      ),
    );
  }
}

/// 显示不同的审核状态
class _SuccessWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    UserRealnameQueryModel model = Provider.of(context, listen: false);
    if (model.data.auditStatus == 'NOT_APPLY') {
      return _NotApplyWidget();
    }
    return _OtherStatusWidget();
  }
}

/// 未申请
class _NotApplyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 12),
      child: ChangeNotifierProvider(
        create: (context) => UserRealnameModel(Provider.of(context, listen: false)),
        child: ListView(
          children: <Widget>[
            _HeaderWidget(),
            _EditWidget(),
            _BottomButtonWidget(),
          ],
        ),
      ),
    );
  }
}

class _HeaderWidget extends StatelessWidget {
  const _HeaderWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 14, right: 8.5),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/cart/img_store.png'),
          fit: BoxFit.fill,
        ),
      ),
      height: 45,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text('实名认证', style: TextStyle(fontSize: 17)),
          Text('提示：请认真核实，以防财产损失', style: TextStyle(fontSize: 12)),
        ],
      ),
    );
  }
}

class _EditWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Theme(
      data: ThemeData.light(),
      child: Material(
        borderRadius: BorderRadius.vertical(
          bottom: Radius.circular(10),
        ),
        child: Consumer<UserRealnameModel>(
          builder: (context, model, child) {
            Me me = Provider.of(context, listen: false);
            // 格式化已经绑定的手机
            var mobileFormat = me.mobile == null || me.mobile.length < 7
                ? null
                : me.mobile.replaceRange(3, 7, '****');
            return Column(
              children: <Widget>[
                _EditItemWidget(
                  hint: '证件号',
                  function: (value) => model.cardNo = value,
                ),
                Divider(height: 1, indent: 12),
                _EditItemWidget(
                  hint: '姓名',
                  function: (value) => model.name = value,
                ),
                Divider(height: 1, indent: 12),
                Row(
                  children: <Widget>[
                    Expanded(
                      child: _EditItemWidget(
                        hint: '请输入$mobileFormat的验证码',
                        function: (value) => model.checkCode = value,
                      ),
                    ),
                    _GetVerifyCodeWidget(),
                  ],
                ),
                Divider(height: 1, indent: 12),
                Container(
                  margin: EdgeInsets.only(top: 9),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      _IDCardItemWidget(
                        imageProvider: model.frontFile == null
                            ? AssetImage('assets/images/auth/img_front.png')
                            : FileImage(model.frontFile),
                        title: '拍摄正面',
                        function: (file) => model.frontFile = file,
                      ),
                      _IDCardItemWidget(
                        imageProvider: model.backFile == null
                            ? AssetImage('assets/images/auth/img_back.png')
                            : FileImage(model.backFile),
                        title: '拍摄反面',
                        function: (file) => model.backFile = file,
                      )
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.all(14),
                  alignment: Alignment.centerLeft,
                  child: Text('上传身份证反正面照片', style: TextStyle(color: Colors.grey)),
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}

class _GetVerifyCodeWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => ReqCodeModel(Provider.of(context, listen: false)),
      child: Consumer<ReqCodeModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return FlatButton(
                onPressed: null,
                child: SizedBox(
                  width: 12,
                  height: 12,
                  child: CircularProgressIndicator(),
                ),
              );
            case ViewState.success:
              return FlatButton(
                onPressed: null,
                child: CountDownText(
                  function: () => model.viewState = ViewState.idle,
                  style: TextStyle(),
                ),
              );
            default:
              return FlatButton(
                onPressed: () => _onGetVerifyCodeClicked(context),
                child: Text('获取验证码'),
              );
          }
        },
      ),
    );
  }

  void _onGetVerifyCodeClicked(BuildContext context) async {
    Me me = Provider.of(context, listen: false);
    ReqCodeModel model = Provider.of(context, listen: false);
    var result = await model.reqCode(ReqCodeModel.REAL_NAME_AUTH, me.mobile);
    switch (result) {
      case ViewState.error:
        showToast(model.errorMessage);
        break;
      default:
        showToast('短信发送成功');
        break;
    }
  }
}

class _EditItemWidget extends StatelessWidget {
  final String hint;
  final Function(String) function;

  _EditItemWidget({
    Key key,
    @required this.hint,
    @required this.function,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      decoration: InputDecoration(
        hintText: hint,
        border: InputBorder.none,
        contentPadding: EdgeInsets.symmetric(vertical: 17, horizontal: 12),
      ),
      onChanged: function,
    );
  }
}

class _IDCardItemWidget extends StatelessWidget {
  final ImageProvider imageProvider;
  final String title;
  final Function(File) function;

  _IDCardItemWidget({
    Key key,
    @required this.imageProvider,
    @required this.title,
    @required this.function,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Stack(
        alignment: Alignment.bottomCenter,
        children: <Widget>[
          Container(
            decoration: BoxDecoration(
              image: DecorationImage(image: imageProvider, fit: BoxFit.fill),
            ),
            width: 164,
            height: 140,
          ),
          Container(
            padding: EdgeInsets.all(9),
            child: Text(
              title,
              style: TextStyle(color: Colors.white, fontSize: 14),
            ),
          ),
        ],
      ),
      onTap: () => _onClicked(context),
    );
  }

  void _onClicked(BuildContext context) async {
    try {
      var result = await ImagePicker.pickImage(
        source: ImageSource.camera,
        maxWidth: 200,
        maxHeight: 200,
      );
      function(result);
    } catch (e) {
      showToast(e.toString());
    }
  }
}

class _BottomButtonWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 90),
      alignment: Alignment.center,
      child: Consumer<UserRealnameModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return LoginButton.busy();
            default:
              return LoginButton(
                title: '认证',
                function: () => _onAuthClicked(context),
              );
          }
        },
      ),
    );
  }

  void _onAuthClicked(BuildContext context) async {
    UserRealnameModel model = Provider.of(context, listen: false);
    var result = await model.userRealname();
    switch (result) {
      case ViewState.error:
        showToast(model.errorMessage);
        break;
      default:
        showToast('认证信息已提交');
        final UserRealnameQueryModel userRealnameQueryModel = Provider.of(context, listen: false);
        userRealnameQueryModel.refreshData();
        break;
    }
  }
}

/// 其他状态
class _OtherStatusWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    UserRealnameQueryModel model = Provider.of(context, listen: false);
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 12),
      child: ListView(
        children: <Widget>[
          _HeaderWidget(),
          Theme(
            data: lightTheme(),
            child: Material(
              borderRadius: BorderRadius.vertical(bottom: Radius.circular(10)),
              child: Column(
                children: <Widget>[
                  ListTile(
                    title: Text('身份证：${model.data.cardNo}'),
                  ),
                  Divider(height: 1, indent: 12),
                  ListTile(
                    title: Text('姓名：${model.data.name}'),
                  ),
                  Divider(height: 1, indent: 12),
                  Container(
                    margin: EdgeInsets.only(top: 8, bottom: 8),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        CachedNetworkImage(
                          imageUrl: model.data.front ?? '',
                          width: 164,
                          height: 140,
                          fit: BoxFit.fill,
                        ),
                        CachedNetworkImage(
                          imageUrl: model.data.back ?? '',
                          width: 164,
                          height: 140,
                          fit: BoxFit.fill,
                        )
                      ],
                    ),
                  ),
                  if (model.data.auditStatus == 'AUDIT_FAIL') ...[
                    Divider(height: 1, indent: 12),
                    ListTile(
                      title: Text('审核失败：${model.data.auditNote}'),
                    ),
                  ]
                ],
              ),
            ),
          ),
          Container(
            padding: EdgeInsets.symmetric(vertical: 90),
            alignment: Alignment.center,
            child: Column(
              children: <Widget>[
                Container(
                  width: 256,
                  height: 64,
                  child: RaisedButton(
                    onPressed: null,
                    child: Text(
                      model.data.auditStatusStr ?? '',
                      style: TextStyle(fontSize: 18),
                    ),
                  ),
                ),
                if (model.data.auditStatus != 'AUDIT_SUCCESS') ...[
                  SizedBox(
                    height: 10,
                  ),
                  ChangeNotifierProvider(
                    create: (context) =>
                        UserRealnameDeleteModel(Provider.of(context, listen: false)),
                    child: Consumer<UserRealnameDeleteModel>(
                      builder: (context, model, child) {
                        switch (model.viewState) {
                          case ViewState.busy:
                            return Container(
                              width: 256,
                              height: 64,
                              child: RaisedButton(
                                onPressed: null,
                                child: CircularProgressIndicator(),
                              ),
                            );
                          default:
                            return Container(
                              width: 256,
                              height: 64,
                              child: RaisedButton(
                                onPressed: () {
                                  _onDeleteClicked(context);
                                },
                                child: Text(
                                  "删除",
                                  style: TextStyle(fontSize: 18),
                                ),
                              ),
                            );
                        }
                      },
                    ),
                  ),
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _onDeleteClicked(BuildContext context) async {
    UserRealnameQueryModel userRealnameQueryModel = Provider.of(context, listen: false);
    UserRealnameDeleteModel userRealnameDeleteModel = Provider.of(context, listen: false);
    final viewState =
        await userRealnameDeleteModel.userRealnameDelete(userRealnameQueryModel.data.id);
    switch (viewState) {
      case ViewState.error:
        showToast(userRealnameDeleteModel.errorMessage);
        break;
      default:
        userRealnameQueryModel.refreshData();
        break;
    }
  }
}
